import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { roomAPI, gameAPI } from '@/api'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { handleApiResponse } from '@/utils/request'

export const useRoomStore = defineStore('room', () => {
  // 房间列表
  const rooms = ref([])
  const currentRoom = ref(null)
  const loading = ref(false)
  
  // 房间统计
  const roomStats = ref({
    totalRooms: 0,
    activeRooms: 0,
    totalPlayers: 0
  })

  // 获取房间列表
  const fetchRoomList = async () => {
    try {
      loading.value = true
      
      
      const result = await roomAPI.getRoomList()
      
      
      // 使用通用响应处理工具
      const roomData = handleApiResponse(result, 'data')
      
      
      // 检查数据类型
      if (!roomData) {
        
        rooms.value = []
        return result
      }
      
      if (!Array.isArray(roomData)) {
        
        rooms.value = []
        return result
      }
      
      // 将API数据映射为组件期望的格式
      const mappedRooms = roomData.map(room => {
        
        
        if (!room || typeof room !== 'object') {
          
          return null
        }
        
        const mappedRoom = {
          roomId: room.id || room.roomId || 'unknown',
          roomName: room.roomName || room.name || '未命名房间',
          status: (room.status || 'waiting').toLowerCase(),
          playerCount: room.currentPlayers || room.playerCount || 0,
          maxPlayers: room.maxPlayers || 5,
          gameDuration: room.gameDuration || room.duration || 2,
          creator: room.creator || room.owner || 'unknown',
          createdAt: room.createdAt,
          startTime: room.startTime
        }
        
        
        return mappedRoom
      }).filter(Boolean) // 过滤掉null值
      
      // 去重处理：根据roomId去重
      const uniqueRooms = []
      const seenRoomIds = new Set()
      
      mappedRooms.forEach(room => {
        if (!seenRoomIds.has(room.roomId)) {
          seenRoomIds.add(room.roomId)
          uniqueRooms.push(room)
        } else {
          
        }
      })
      
      rooms.value = uniqueRooms
      
      
      
      roomStats.value = {
        totalRooms: rooms.value.length,
        activeRooms: rooms.value.filter(room => room.status === 'waiting' || room.status === 'playing').length,
        totalPlayers: rooms.value.reduce((sum, room) => sum + (room.playerCount || 0), 0)
      }
      
      
      return result
    } catch (error) {
      
      rooms.value = []
      throw error
    } finally {
      loading.value = false
    }
  }

  // 创建房间
  const createRoom = async (roomData) => {
    try {
      loading.value = true
      const result = await roomAPI.createRoom(roomData)
      const createData = handleApiResponse(result, 'data')
      
      // 如有需要可在此用 createData 派生本地结构
      
      ElMessage.success('房间创建成功！')
      
      // 不立即刷新房间列表，避免重复显示
      // 房间列表会在页面自动刷新时更新
      
      // 返回包含创建房间信息的完整结果
      return {
        ...result,
        data: createData
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取房间详情
  const fetchRoomInfo = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.getRoomInfo(roomId)
      const roomData = handleApiResponse(result, 'data')
      
      // 将API数据映射为组件期望的格式，并尽可能带上成员列表
      const mappedMembers = Array.isArray(roomData?.members)
        ? roomData.members
        : (Array.isArray(roomData?.players) ? roomData.players : [])
      
      // 标准化成员数据（以服务端 creatorId 判定房主，避免顺序误判）
      const creatorIdFromApi = roomData?.creatorId || roomData?.creator?.id || roomData?.creatorId?.id || null
      const normalizedMembers = mappedMembers.map((member, index) => {
        const id = member?.id || member?.userId || `user_${index}` || `temp_${Date.now()}_${index}`
        const isHost = creatorIdFromApi ? String(id) === String(creatorIdFromApi) : (index === 0)
        return ({
          id,
          name: member?.name || member?.username || member?.nickname || `User_${member?.id?.slice(-8) || index}`,
          avatar: member?.avatar || member?.avatarUrl || null,
          color: member?.color || null,
          // 等级/称号：只有服务端提供才设置，否则保持 undefined，避免误显示默认值
          level: (typeof member?.level === 'number') ? member.level : undefined,
          title: (typeof member?.title === 'string' && member.title) ? member.title : undefined,
          isReady: Boolean(member?.isReady ?? member?.ready ?? false),
          isHost
        })
      })
      
      currentRoom.value = roomData ? {
        roomId: roomData.id,
        roomName: roomData.roomName,
        status: roomData.status?.toLowerCase() || 'waiting',
        playerCount: roomData.currentPlayers || roomData.playerCount || (normalizedMembers?.length || 0),
        maxPlayers: roomData.maxPlayers || 5,
        gameDuration: roomData.gameDuration || roomData.duration || 2,
        creator: roomData.creator || roomData.creatorName,
        creatorId: creatorIdFromApi || roomData.creatorId || null,
        createdAt: roomData.createdAt,
        startTime: roomData.startTime,
        members: normalizedMembers
      } : null
      
      return result
    } catch (error) {
      // 如果是 404（房间不存在），优雅处理：清空当前房间并提示
      const status = error?.response?.status
      if (status === 404) {
        currentRoom.value = null
        
        return { success: false, status: 404 }
      }
      
      throw error
    } finally {
      loading.value = false
    }
  }

  // ------- 成员管理（供实时事件与组件统一调用） -------
  const setMembers = (list = []) => {
    if (!currentRoom.value) return
    // 确保只有一个房主
    const normalizedMembers = Array.isArray(list) ? list.map((member, index) => ({
      id: member?.id || member?.userId || `user_${index}` || `temp_${Date.now()}_${index}`,
      name: member?.name || member?.username || member?.nickname || `User_${member?.id?.slice(-8) || index}`,
      avatar: member?.avatar || member?.avatarUrl || null,
      color: member?.color || null, // 保留颜色信息
      isReady: Boolean(member?.isReady ?? member?.ready ?? false),
      isHost: Boolean(member?.isHost ?? member?.host ?? false) && index === 0 // 只有第一个成员是房主
    })) : []
    
    currentRoom.value.members = normalizedMembers
  }

  const addOrUpdateMember = (member) => {
    if (!currentRoom.value) return
    if (!Array.isArray(currentRoom.value.members)) currentRoom.value.members = []
    
    const id = member?.id || member?.userId || null
    const name = member?.name || member?.username || member?.nickname || `User_${id?.slice(-8) || 'unknown'}`
    
    const idx = currentRoom.value.members.findIndex(m => (m.id || m.userId) === id)
    const normalized = {
      id,
      name,
      avatar: member?.avatar || member?.avatarUrl || null,
      color: member?.color || null, // 保留颜色信息
      level: typeof member?.level === 'number' ? member.level : undefined,
      title: member?.title || undefined,
      isReady: Boolean(member?.isReady ?? member?.ready ?? false),
      // 优先根据 currentRoom.creatorId 判定房主；服务端未带时才回退 member 标记
      isHost: currentRoom.value?.creatorId ? (String(id) === String(currentRoom.value.creatorId)) : Boolean(member?.isHost ?? member?.host ?? false)
    }
    
    if (idx >= 0) {
      // 更新现有成员
      currentRoom.value.members[idx] = { ...currentRoom.value.members[idx], ...normalized }
    } else {
      // 添加新成员
      currentRoom.value.members.push(normalized)
    }
    
    // 统一校正 isHost，确保与 creatorId 一致
    if (currentRoom.value?.creatorId) {
      currentRoom.value.members = currentRoom.value.members.map(m => ({
        ...m,
        isHost: String(m.id) === String(currentRoom.value.creatorId)
      }))
    }
  }

  const updateMemberReady = (idOrName, isReady) => {
    if (!currentRoom.value || !Array.isArray(currentRoom.value.members)) return
    const target = String(idOrName || '').toLowerCase()
    const idx = currentRoom.value.members.findIndex(m => {
      const mid = String(m.id || m.userId || '').toLowerCase()
      const mname = String(m.name || '').toLowerCase()
      return (mid && mid === target) || (mname && mname === target)
    })
    if (idx >= 0) {
      // 修改副本并整体替换，确保触发响应式
      const copied = [...currentRoom.value.members]
      copied[idx] = { ...copied[idx], isReady: !!isReady }
      currentRoom.value.members = copied
    }
  }

  const removeMember = (idOrName) => {
    if (!currentRoom.value || !Array.isArray(currentRoom.value.members)) return
    const target = String(idOrName || '').toLowerCase()
    const idx = currentRoom.value.members.findIndex(m => {
      const mid = String(m.id || m.userId || '').toLowerCase()
      const mname = String(m.name || '').toLowerCase()
      return mid === target || mname === target
    })
    if (idx >= 0) currentRoom.value.members.splice(idx, 1)
  }

  // 加入房间
  const joinRoom = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.joinRoom(roomId)
      // 如果服务端提示已在该房间，则不再弹错误，直接认为成功
      const serverMsg = result?.message || ''
      if (/已经在房间/.test(serverMsg)) {
        // 同房间，无需重复提示
      } else {
        ElMessage.success('成功加入房间！')
      }
      
      // 更新房间信息
      await fetchRoomInfo(roomId)
      
      return result
    } catch (error) {
      const status = error?.response?.status
      const msg = error?.response?.data?.message || error?.message || ''
      // 如果后端提示“已经在房间”
      if (msg.includes('已经在房间')) {
        // 1) 如果就是目标房间：视为成功，只刷新房间信息
        if (!currentRoom.value || currentRoom.value.roomId === roomId) {
          await fetchRoomInfo(roomId)
          return { success: true, message: 'already in room' }
        }
        // 2) 如果在其他房间：先离开，再加入目标房间
        try {
          if (currentRoom.value?.roomId) {
            await leaveRoom(currentRoom.value.roomId)
          }
          const retry = await roomAPI.joinRoom(roomId)
          ElMessage.success('成功加入房间！')
          await fetchRoomInfo(roomId)
          return retry
        } catch (retryErr) {
          const retryStatus = retryErr?.response?.status
          const retryMsg = retryErr?.response?.data?.message || retryErr?.message || ''
          if (retryStatus === 400) {
            if (retryMsg) ElMessage.warning(retryMsg)
            try { await fetchRoomInfo(roomId) } catch {}
            return { success: false, message: retryMsg, status: retryStatus }
          }
          throw retryErr
        }
      }
      // 其它 400 业务性错误：给出提示但不抛出
      if (status === 400) {
        if (msg) ElMessage.warning(msg)
        // 同步刷新房间信息，避免界面不同步
        try { await fetchRoomInfo(roomId) } catch {}
        return { success: false, message: msg, status }
      }
      // 其他真正的错误再打印
      
      throw error
    } finally {
      loading.value = false
    }
  }

  // 离开房间
  const leaveRoom = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.leaveRoom(roomId)
      ElMessage.success('已离开房间')
      
      // 清除当前房间
      currentRoom.value = null
      
      // 立即刷新房间列表，确保大厅人数/状态即时更新
      try { await fetchRoomList() } catch (_) {}
      
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 开始游戏
  const startGame = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.startGame(roomId)
      ElMessage.success('游戏开始！')
      
      // 更新房间信息
      await fetchRoomInfo(roomId)
      
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 结束游戏
  const endGame = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.endGame(roomId)
      ElMessage.success('游戏结束')
      
      // 更新房间信息
      await fetchRoomInfo(roomId)
      
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 将当前房间所有成员的准备状态设置为给定值（默认未准备）
  const setAllMembersReady = (isReady = false) => {
    try {
      if (!currentRoom.value || !Array.isArray(currentRoom.value.members)) return
      const next = currentRoom.value.members.map(m => ({ ...m, isReady: !!isReady }))
      currentRoom.value.members = next
    } catch (_) {}
  }

  // 同步更新房间状态到 currentRoom 与 rooms 列表
  const updateRoomStatus = (roomId, status) => {
    try {
      const normalized = String(status || '').toLowerCase()
      if (currentRoom.value && String(currentRoom.value.roomId) === String(roomId)) {
        currentRoom.value.status = normalized || currentRoom.value.status || 'waiting'
      }
      if (Array.isArray(rooms.value)) {
        const idx = rooms.value.findIndex(r => String(r.roomId) === String(roomId))
        if (idx >= 0) {
          rooms.value[idx] = { ...rooms.value[idx], status: normalized || rooms.value[idx].status || 'waiting' }
        }
      }
    } catch (_) {}
  }

  // 删除房间
  const deleteRoom = async (roomId) => {
    try {
      loading.value = true
      const result = await roomAPI.deleteRoom(roomId)
      ElMessage.success('房间已删除')
      
      // 刷新房间列表
      await fetchRoomList()
      
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取房间统计
  const fetchRoomStats = async (roomId) => {
    try {
      loading.value = true
      const result = await gameAPI.getRoomStats(roomId)
      handleApiResponse(result, 'data')
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取房间排行榜
  const fetchRoomLeaderboard = async (roomId) => {
    try {
      loading.value = true
      const result = await gameAPI.getRoomLeaderboard(roomId)
      handleApiResponse(result, 'data')
      return result
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 计算属性
  const waitingRooms = computed(() => {
    return rooms.value.filter(room => room.status === 'waiting')
  })

  const playingRooms = computed(() => {
    return rooms.value.filter(room => room.status === 'playing')
  })

  const finishedRooms = computed(() => {
    return rooms.value.filter(room => room.status === 'finished')
  })

  const isInRoom = computed(() => {
    return !!currentRoom.value
  })

  const isRoomOwner = computed(() => {
    if (!currentRoom.value || !currentRoom.value.owner) return false
    // 这里需要根据实际的用户ID来判断
    return currentRoom.value.owner.id === 'current-user-id'
  })

  // 检查用户是否在任何房间中
  const isUserInAnyRoom = computed(() => {
    return !!currentRoom.value
  })

  // 获取用户当前房间ID
  const getUserCurrentRoomId = () => {
    return currentRoom.value?.roomId || null
  }

  // 检查并恢复用户房间状态
  const checkAndRestoreUserRoom = async () => {
    // 这里可以添加从本地存储或其他地方恢复用户房间状态的逻辑
    // 例如：检查用户是否在某个房间中，如果是则重新获取房间信息
    if (currentRoom.value?.roomId) {
      try {
        await fetchRoomInfo(currentRoom.value.roomId)
      } catch (error) {
        // 如果房间不存在，清除当前房间状态
        currentRoom.value = null
      }
    }
  }

  // 实时更新游戏玩家列表（根据房间成员信息）
  const updateGamePlayersFromMembers = (gameStore) => {
    if (!currentRoom.value?.members || !Array.isArray(currentRoom.value.members)) {
      return
    }

    console.log('更新游戏玩家列表，成员数量:', currentRoom.value.members.length)
    
    // 统一的备用颜色调色板（与后端保持一致顺序）
    const palette = [
      '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
      '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
    ]
    const used = new Set()
    // 读取现有玩家的颜色，用于保持稳定
    const prevById = new Map(Array.isArray(gameStore?.players) ? gameStore.players.map(p => [String(p.id), p]) : [])
    const isValidColor = (c) => typeof c === 'string' && /^#?[0-9A-Fa-f]{6}$/.test(c)

    // 将房间成员转换为游戏玩家格式，优先使用后端颜色；若缺失或重复则分配唯一颜色
    const gamePlayers = currentRoom.value.members.map((member, index) => {
      const playerId = member.id || member.userId || `player_${index}`
      const playerName = member.name || member.username || member.nickname || `玩家${index + 1}`
      
      // 颜色分配策略：
      // 1) 若已有玩家颜色，优先保持不变
      // 2) 否则使用服务端颜色（有效且未被占用）
      // 3) 否则从调色板分配一个未占用颜色
      let color = ''
      const prev = prevById.get(String(playerId))
      if (prev && isValidColor(prev.color)) {
        color = prev.color
      } else if (isValidColor(member.color) && !used.has(member.color)) {
        color = member.color
      } else {
        const available = palette.find(c => !used.has(c))
        color = available || '#6B7280'
      }
      used.add(color)
      
      // 获取头像URL
      let avatarUrl = ''
      if (member.avatar) {
        try {
          // 与大厅一致：优先通过 userStore 的预览方法（同步调用）
          const u = useUserStore()
          if (typeof u.getAvatarPreviewUrl === 'function') {
            avatarUrl = u.getAvatarPreviewUrl(member.avatar)
          }
        } catch (_) {}
      }
      
      return {
        id: playerId,
        name: playerName,
        color: color,
        score: 0, // 初始分数
        area: 0,  // 初始面积
        isActive: true, // 在房间中的玩家都是活跃的
        isReady: Boolean(member.isReady),
        isHost: Boolean(member.isHost),
        avatar: avatarUrl, // 同步头像（预览地址）
        level: typeof member.level === 'number' ? member.level : 1,
        title: member.title || '墨痕初绽'
      }
    })
    
    // 更新游戏store中的玩家列表
    if (gameStore && typeof gameStore.setPlayers === 'function') {
      gameStore.setPlayers(gamePlayers)
    } else {
      console.warn('gameStore.setPlayers方法不可用')
    }
    
    console.log('游戏玩家列表更新完成:', gamePlayers.length, '个玩家')
  }

  // 获取当前房间的实时玩家数量
  const getCurrentRoomPlayerCount = () => {
    if (!currentRoom.value?.members) return 0
    return currentRoom.value.members.length
  }

  // 获取当前房间的活跃玩家数量（已准备的玩家）
  const getCurrentRoomActivePlayerCount = () => {
    if (!currentRoom.value?.members) return 0
    return currentRoom.value.members.filter(member => member.isReady).length
  }

  return {
    // 状态
    rooms,
    currentRoom,
    loading,
    roomStats,
    
    // 方法
    fetchRoomList,
    createRoom,
    fetchRoomInfo,
    joinRoom,
    leaveRoom,
    startGame,
    endGame,
    deleteRoom,
    fetchRoomStats,
    fetchRoomLeaderboard,
    updateRoomStatus,
    setAllMembersReady,
    
    // 成员管理方法
    setMembers,
    addOrUpdateMember,
    updateMemberReady,
    removeMember,
    
    // 计算属性
    waitingRooms,
    playingRooms,
    finishedRooms,
    isInRoom,
    isRoomOwner,
    isUserInAnyRoom,
    getUserCurrentRoomId,
    checkAndRestoreUserRoom,
    updateGamePlayersFromMembers,
    getCurrentRoomPlayerCount,
    getCurrentRoomActivePlayerCount
  }
}) 